using Application.Abstractions.Authentication;
using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Users;
using Microsoft.EntityFrameworkCore;
using SharedKernel;

namespace Application.Users.Register;

internal sealed class RegisterUserCommandHandler(
    IApplicationDbContext context,
    IPasswordHasher passwordHasher,
    IDateTimeProvider dateTimeProvider,
    IUnitOfWork unitOfWork) : ICommandHandler<RegisterUserCommand, Guid>
{
    public async ValueTask<Result<Guid>> Handle(RegisterUserCommand command, CancellationToken cancellationToken)
    {
        // 检查邮箱是否已存在
        bool emailExists = await context.Users
            .AnyAsync(u => u.Email == command.Email, cancellationToken);

        if (emailExists)
        {
            return Result.Failure<Guid>(UserErrors.EmailNotUnique);
        }

        // 创建新用户 - 事件会在构造函数中自动触发
        var user = new User(
            command.Email,
            command.FirstName,
            command.LastName,
            passwordHasher.Hash(command.Password),
            dateTimeProvider);

        context.Users.Add(user);

        await unitOfWork.SaveChangesAsync(cancellationToken);

        return user.Id;
    }
}
